<template>
  <div>
    <div v-show="tabIndex==='2d'" id="container_2d" class="mapBox" ref="container_2d"></div>
    <div v-show="tabIndex==='3d'" id="container_3d" class="mapBox" ref="container_3d"></div>
    <marker-set-panel class="markerSetPanel" :markerSetData='markerSetData' v-model="showUlFlag"
                      @selectIcon="showSelectIcon"
                      @showList="showList"></marker-set-panel>
    <location-panel class="locationPanel" v-model="searchVal" :mapType="tabIndex" :lnglat="zoomAndCenter.center"
                    @zoomAndCenter="setZoomAndCenter"></location-panel>
    <anchors-bar v-model="achorsInfo"
                 :mapScaleArr="mapScaleArr"
                 v-if="showAnchors"
                 :mapType="tabIndex"
                 :currentRelationUrl="currentRelationUrl"
                 @editData="editDataFn"
                 @clickEvent="clickEvent"></anchors-bar>
    <camera-list v-if='false' class="cameraList"></camera-list>
    <!--<div :class="{'ancSelectBox': openAndCloseFlag, 'ancUnSelectBox': !openAndCloseFlag}">-->
    <!--<span @click="openAndClose">-->
    <!--<img src="../../../assets/images/mapIconTest/selected.png" alt="">-->
    <!--</span>-->
    <!--</div>-->
    <marker-list v-if="openAndCloseFlag && ancSelectMarkers.length > 0" class="markerList"
                 v-model="ancSelectMarkers"></marker-list>
    <div class="linkWrap" v-dragable v-show="showAnchors && linkFlag">
      <span class="iconClose" @click="iframeHide">
        ×
      </span>
      <iframe class="iframeWrap" :src="iframeSrc" ref="iframeLink" frameborder="0"></iframe>
    </div>
  </div>
</template>
<script>
  import markerSetPanel from '@/components/panel/markerSetPanel'
  import locationPanel from '@/components/panel/locationPanel'
  import anchorsBar from '@/components/panel/anchorsBar'
  import cameraList from '@/components/demo/cameraList'
  import markerList from '@/components/demo/markerList'
  export default {
    name: 'demo',
    data () {
      return {
        editData: '',
        linkFlag: false,
        iframeSrc: '',
        showUlFlag: false,
        ancSelectMarkers: [], // 矩形选中 标注
        openAndCloseFlag: false, // 开启关闭矩形选中
        mouseTool: '',
        selectZoomMouseDownHandler: '',
        selectZoomDrawHandler: '',
        showAnchors: false,
        achorsInfo: {
          anchorStatus: '01',
          anchorName: '',
          anchorDesc: '',
          mapScale: '',
          latitude: '',
          longitude: '',
          areaCityId: '',
          areaCountyId: '',
          areaTownId: '',
          areaWayId: ''
        },
        oldMapBounds: {
          northeast: {lng: '', lat: ''},
          southwest: {lng: '', lat: ''}
        },
        selectMarker: '',
        searchVal: '',
        // 标注面板信息列表
        markerSetData: {
          recordList: [], // 标注面板图标信息
          maximum: 6 // 面板一行显示最大条数
        },
        markerSetData2D: {
          id: '2d',
          recordList: [], // 标注面板图标信息
          maximum: 6 // 面板一行显示最大条数
        },
        markerSetData3D: {
          id: '3d',
          recordList: [], // 标注面板图标信息
          maximum: 6 // 面板一行显示最大条数
        },
        isMap2deventBind: false,
        isMap3dEventBind: false,
        clickCancel: true,
        listenerFlag: false,
        map: '',
        markers: [],
        pointerCheckedList: '',
        zoomAndCenter: {
          zoom: '',
          center: []
        },
        throttleEventHandle: '',
        map2D: '',
        map3D: '',
        currentMarkerIdList: [],
        mapScaleArr: [],
        selectMarkerOrig: null,
        anchorsIconUrlList: {},
        markerChangeTag: 'normal',
        cluster: null,
        clusterMarkers: [],
        extMarker: [],
        geocoder: {},
        placeSearch: {},
        street: '',
        road: '',
        currentRelationUrl: ''
      }
    },
    props: {
      tabIndex: {
        type: String
      }
    },
    methods: {
      editDataFn (e) {
        this.editData = e
        console.log('editDataFn', e)
      },
      messageHandler (res) {
        if (res.data === 'success') {
          this.pointDetailGet(this.selectMarker.getExtData().anchorId).then(res => {
            console.log(res)
            this.setMarkerState({
              marker: this.selectMarker,
              changeArr: [{
                label: 'anchorStatus',
                value: '03'
              }, {
                label: 'relationBusinessData',
                value: res.relationBusinessData
              }]
            })
            this.selectMarkerOrig.anchorStatus = res.anchorStatus
            this.selectMarkerOrig.relationBusinessData = res.relationBusinessData
          })
        }
      },
      addMessageListener () {
        window.addEventListener('message', this.messageHandler)
      },
      iframeHide () {
        this.linkFlag = false
        // window.removeEventListener('message', this.messageHandler)
      },
      iframeShow (type) {
        this.linkFlag = type
        var extData = this.selectMarker.getExtData()
        var accessToken = window.localStorage.getItem('accessToken')
        var accessTokenKey = window.localStorage.getItem('accessTokenKey')
        var clientId = window.localStorage.getItem('clientId')
        var anchorId = extData.anchorId
        var height, width
        var el = this.$refs.iframeLink
        var replaceStr
        if (type === 'link') {
          height = this.pointerCheckedList.relationWindowHeight
          width = this.pointerCheckedList.relationWindowWidth
          var relationUrl = this.pointerCheckedList.relationUrl.replace(/(\$\{[a-zA-Z]*\})/g, (e) => {
            switch (e) {
              case '${cid}':
              replaceStr = clientId
              break
              case '${ak}':
              replaceStr = accessTokenKey
              break
              case '${token}':
              replaceStr = accessToken
              break
              case '${anchorId}':
              replaceStr = anchorId
              break
              default:
              break
            }
            return replaceStr
          })
          this.iframeSrc = relationUrl
          // 禁用iframe监听 this.addMessageListener()
        } else {
          height = this.pointerCheckedList.entranceWindowHeight
          width = this.pointerCheckedList.entranceWindowWidth
          this.iframeSrc = this.pointerCheckedList.entranceUrl.replace('${id}', extData.relationBusinessData)
        }
        el.height = height || 500
        el.width = width || 500
        console.log('iframe地址', this.iframeSrc)
      },
      /**
       * 新开标签页
       * @author chend(cdhahaha@163.com)
       * @createDate 2018-09-21
       * @param      {标签页地址}   url    [description]
       * @param      {标签页高度}   height [description]
       * @param      {标签页宽度}   width  [description]
       */
      openWindow (url, height = 500, width = 500) {
        var iTop = (window.screen.availHeight - 30 - height) / 2
        var iLeft = (window.screen.availWidth - 10 - width) / 2
        window.open(url, "newWindow", `height=${height},width=${width},left=${iLeft},top=${iTop},menubar=0,scrollbars=1,resizable=1,status=1,titlebar=0,toolbar=0,location=1`)
      },
      qtShow (type) {
        var extData = this.selectMarker.getExtData()
        var accessToken = window.localStorage.getItem('accessToken')
        var accessTokenKey = window.localStorage.getItem('accessTokenKey')
        var clientId = window.localStorage.getItem('clientId')
        var anchorId = extData.anchorId
        var replaceStr
        var height, width
        if (type === 'link') {
          height = this.pointerCheckedList.relationWindowHeight
          width = this.pointerCheckedList.relationWindowWidth
          var relationUrl = this.pointerCheckedList.relationUrl.replace(/(\$\{[a-zA-Z]*\})/g, (e) => {
            switch (e) {
              case '${cid}':
              replaceStr = clientId
              break
              case '${ak}':
              replaceStr = accessTokenKey
              break
              case '${token}':
              replaceStr = accessToken
              break
              case '${anchorId}':
              replaceStr = anchorId
              break
              default:
              break
            }
            return replaceStr
          })
          this.iframeSrc = relationUrl
        } else {
          height = this.pointerCheckedList.entranceWindowHeight
          width = this.pointerCheckedList.entranceWindowWidth
          this.iframeSrc = this.pointerCheckedList.entranceUrl.replace('${id}', extData.relationBusinessData)
        }
        this.openWindow(this.iframeSrc, height, width)
      },
      /**
       * 地图scale组件初始化
       */
      scaleTool (ctx) {
        AMap.plugin(['AMap.Scale'], function () {
          ctx.addControl(new AMap.Scale({
            position: 'tl',
          }))
        })
      },
      /**
       * 地图zoom组件初始化
       */
      zoom (ctx){
        AMapUI.loadUI(['control/BasicControl'], function (BasicControl) {
          let zoomCtrl1 = new BasicControl.Zoom({
            position: 'tl',
            theme: 'dark'
          })
          ctx.addControl(zoomCtrl1);
        })
      },
      /**
       * 为地图绑定搜索和中心点定位 功能
       * @param ctx 地图对象
       * @param inputId 搜索框id
       * @constructor
       */
      KeywordLocationMapCenterPoint (ctx, inputId) {
        AMapUI.loadUI(['misc/PoiPicker'], PoiPicker => {
          let poiPicker = new PoiPicker({
            input: inputId
          })
          //初始化poiPicker
          this.marker = new AMap.Marker()
          //选取了某个POI
          poiPicker.on('poiPicked', poiResult => {
            let poi = poiResult.item
            this.marker.setMap(ctx)
            this.searchVal = poi.name
            if (!poi.location) {
              return
            }
            this.marker.setMap(ctx)
            this.marker.setPosition(poi.location)
            let extData = {type: 'center'}
            this.marker.setExtData(extData) //给标记点添加type属性
            ctx.setZoomAndCenter(19, this.marker.getPosition())
          })
        })
      },
      /**
       * 获取地图初始化zoom 和 center
       */
      getZoomAndCenter () {
        var zoom = this.map.getZoom()
        var center = [this.map.getCenter().lng, this.map.getCenter().lat]
        this.zoomAndCenter['zoom'] = zoom
        this.zoomAndCenter['center'] = center
      },
      /**
       * 设置地图初始化zoom 和 center
       */
      setZoomAndCenter ({zoom, center} = {}) {
        let extData = {type: 'center'}
        center = [...center]
        this.map.setZoomAndCenter(zoom, center)
        this.marker.setPosition(center)
        this.marker.setMap(null)
        this.marker.setMap(this.map);
        this.marker.setExtData(extData) //给标记点添加type属性
      },
      /**
       * 锚点类型点击切换回调
       */
      showSelectIcon (data) {
        this.pointerCheckedList = data
        this.currentRelationUrl = data.relationUrl
      },
      /**
       * 锚点显示隐藏 1.未编辑是否显示 2.未关联是否显示
       * @author chend(cdhahaha@163.com)
       * @createDate 2018-08-27
       * @param      {Boolean}   checked     是否选中
       * @param      {String}   anchorStatus 锚点状态
       */
      showCheckedFn (checked, anchorStatus) {
        if (!checked) {
          this.clusterMarkers.forEach(v => {
            if (v.getExtData().anchorStatus === anchorStatus) {
              this.cluster.removeMarker(v)
            }
          })
        } else {
          this.clusterMarkers.forEach(v => {
            if (v.getExtData().anchorStatus === anchorStatus) {
              this.cluster.addMarker(v)
            }
          })
        }
      },
      /**
       * 姓名的显示隐藏
       * @author chend(cdhahaha@163.com)
       * @createDate 2018-08-27
       * @param      {Boolean}   checked     是否选中
       */
      showNameFn (checked) {
        if (checked) {
          this.cluster.getMarkers().forEach(v => {
            v.setLabel({
              content: v.getExtData().anchorName || '未命名'
            })
          })
        } else {
          this.cluster.getMarkers().forEach(v => {
            v.setLabel({
              content: ''
            })
          })
        }
      },
      /**
       * 比例的显示隐藏
       * @author chend(cdhahaha@163.com)
       * @createDate 2018-08-27
       */
      showBiliFn (data) {
        let oldShowListLen = data.oldShowListLen || 0
        let actualMapScale = parseInt(this.$utils.MAPSCALEMAP[parseInt(this.map.getZoom())])
        data.oldShowListLen = data.showList.length
        if (data.showList.length > oldShowListLen) {
          this.markersInit('all')
        } else {
          this.extMarker.forEach(v => {
            var extData = v.getExtData()
            if (this.pointerCheckedList.showList.indexOf(extData.mapScale) > -1) {
              this.cluster.addMarker(v)
            } else {
              /**
               * 未强制显示的比例，如果处于当前比例及以下，依然显示。
               * @author chend(cdhahaha@163.com)
               */
              if (actualMapScale > parseInt(extData.mapScale)) {
                this.cluster.removeMarker(v)
              } else {
                this.cluster.addMarker(v)
              }
            }
          })
        }
      },
      /**
       * 锚点类型上拉显示 类型checkbox change事件回调
       */
      showList (data, name) {
        console.log(data, name)
        let actualMapScale = parseInt(this.$utils.MAPSCALEMAP[parseInt(this.map.getZoom())])
        switch (name) {
          case 'showUnEdit':
            if (this.pointerCheckedList.showCheck.indexOf('showUnEdit') > -1) {
              this.markersInit('all')
              return
            }
            break
          case 'showUnLink':
            if (this.pointerCheckedList.showCheck.indexOf('showUnLink') > -1) {
              this.markersInit('all')
              return
            }
            break
          case 'showAll':
          case 'showBili':
            let oldShowListLen = data.oldShowListLen || 0
            data.oldShowListLen = data.showList.length
            if (data.showList.length > oldShowListLen) {
              this.markersInit('all')
              return
            }
            break
        }
        let removeMarkers = []
        this.map.getAllOverlays().forEach(v => { // this.cluster.getMarkers() this.map.getAllOverlays()
          var extData = v.getExtData()
          switch (extData.anchorStatus) {
            case '01':
              if (this.pointerCheckedList.showCheck.indexOf('showUnEdit') === -1) {
//                this.currentMarkerIdList.splice(this.currentMarkerIdList.indexOf(extData.anchorId), 1)
//                removeMarkers.push(v)
                v.hide()
              } else {
                v.show()
              }
              break
            case '02':
              if (this.pointerCheckedList.showCheck.indexOf('showUnLink') === -1) {
//                this.currentMarkerIdList.splice(this.currentMarkerIdList.indexOf(extData.anchorId), 1)
//                removeMarkers.push(v)
                v.hide()
              } else {
                v.show()
              }
              break
            case '03':
              if ((this.pointerCheckedList.showList.indexOf(extData.mapScale) === -1) && (actualMapScale > parseInt(extData.mapScale))) {
//                this.currentMarkerIdList.splice(this.currentMarkerIdList.indexOf(extData.anchorId), 1)
//                removeMarkers.push(v)
                v.hide()
              } else {
                v.show()
              }
              break
          }
          v.setLabel({
            content: data.showCheck.indexOf('showName') > -1 ? v.getExtData().anchorName || '未命名' : ''
          })
        })
//        this.cluster.removeMarkers(removeMarkers)
      },
      /**
       * 锚点content根据不同状态动态创建
       */
      markerHtml ({isSelect, anchorIconUrl, anchorStatus}) {
        switch (anchorStatus) {
          case '02':
            var markerStateHtml = `<span class="iconMarkerUnlink"></span>`
            break
          case '03':
            markerStateHtml = ``
            break
          case '01':
          default:
            markerStateHtml = `<span class="iconMarkerUnedit"></span>`
            break
        }
        return `<div class="${isSelect ? 'markerSelect' : 'markerUnSelect'}">${markerStateHtml}<img style="width: 33px; height: 29px" src="${anchorIconUrl}" alt=""></div>`
      },
      /**
       * 设置标注状态
       * @author chend(cdhahaha@163.com)
       * @createDate 2018-08-29
       * @param      {Object}   options.marker   要作用的标注
       * @param      {Array}   options.changeArr 改变的状态 {label: '', value: ''}
       */
      setMarkerState ({marker, changeArr}) {
        var extData = marker.getExtData()
        var labelArr = changeArr.map(change => {
          extData[change.label] = change.value || extData[change.label]
          return change.label
        })
        var iconChange = (labelArr.indexOf('anchorStatus') > -1) || (labelArr.indexOf('isSelect') > -1)
        var labelChange = labelArr.indexOf('anchorName') > -1
        /* marker.setContent(this.markerHtml({
         isSelect: extData.isSelect,
         anchorIconUrl: this.anchorsIconUrlList[extData.anchorTypeId],
         anchorPointName: extData.anchorPointName,
         anchorStatus: extData.anchorStatus,
         })) */
        if (iconChange) {
          marker.setIcon(`${this.anchorsIconUrlList[extData.anchorTypeId]}&status=${extData.anchorStatus}${extData.isSelect ? 1 : 0}`)
        }
        if (labelChange) {
          marker.setLabel({
            content: this.pointerCheckedList.showCheck.indexOf('showName') > -1 ? extData.anchorName || '未命名' : '',
            offset: new AMap.Pixel(0, 60)
          })
        }
      },
      /**
       * 标注事件回调函数。用于处理标注选中事件的相关逻辑
       * @author chend(cdhahaha@163.com)
       * @createDate 2018-08-07
       * @param      {Event}   e 事件对象
       */
      async selectMarkerFn (e) {
        var nowMarker = e.target
        var nowExtData = nowMarker.getExtData()
        this.showUlFlag = !this.showUlFlag
        if (this.selectMarker) {
          this.markerChangeTag = 'normal'
          var lastExtData = this.selectMarker.getExtData()
          let tmpLastExtData = JSON.parse(JSON.stringify(lastExtData))
          delete tmpLastExtData.isSelect
          if (this.selectMarkerOrig) {
            delete this.selectMarkerOrig.isSelect
          }
          if (this.selectMarkerOrig && !((e.type !== 'click') && (lastExtData.anchorId === nowExtData.anchorId)) && !this.$utils.cmp(this.selectMarkerOrig, tmpLastExtData)) {
            this.markerChangeTag = 'wait'
            await this.$confirm('当前点编辑未保存, 是否保存?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              closeOnClickModal: false,
              type: 'warning'
            }).then(() => {
                nowMarker.setPosition([nowExtData.longitude, nowExtData.latitude])
                return this.markerChangeTag = this.markerUpdate()
              }
            ).catch(() => {
                nowMarker.setPosition([nowExtData.longitude, nowExtData.latitude])
                this.selectMarker.setExtData(this.selectMarkerOrig)
                this.selectMarker.setPosition([this.selectMarkerOrig.longitude, this.selectMarkerOrig.latitude])
              }
            )
            if (this.markerChangeTag === 'null') return
          }
          console.log(lastExtData, lastExtData.anchorId, nowExtData.anchorId)
          lastExtData.isSelect = lastExtData.anchorId === nowExtData.anchorId ? lastExtData.isSelect : false
          this.setMarkerState({
            marker: this.selectMarker,
            changeArr: [{label: 'anchorStatus', value: lastExtData.anchorStatus}]
          })
        }
        if (!nowExtData.isSelect) {
          this.selectMarkerOrig = JSON.parse(JSON.stringify(nowExtData))
        }
        nowExtData.isSelect = e.type === 'click' ? !nowExtData.isSelect : true
        this.setMarkerState({marker: nowMarker, changeArr: [{label: 'anchorStatus', value: nowExtData.anchorStatus}]})
        this.selectMarker = nowMarker
        this.achorsInfo = nowExtData
        this.showAnchors = nowExtData.isSelect
        if (this.achorsInfo.anchorStatus !== '01')  {
          if (!this.showAnchors) {
            this.linkFlag = false
          }
          if (this.linkFlag) {
            this.iframeShow(this.linkFlag)
          }
        }
      },
      /**
       * 向地图打点方法
       */
      setMarker ({extData}) {
        var marker = new AMap.Marker({
          /* content: this.markerHtml({
           isSelect: false,
           anchorIconUrl: this.anchorsIconUrlList[extData.anchorTypeId],
           anchorStatus: extData.anchorStatus
           }), */
          icon: `${this.anchorsIconUrlList[extData.anchorTypeId]}&status=${extData.anchorStatus}${extData.isSelect ? 1 : 0}`,
          height: extData.height,
          label: {
            content: this.pointerCheckedList.showCheck.indexOf('showName') > -1 ? extData.anchorName || '未命名' : '',
            offset: new AMap.Pixel(0, 60)
          },
          // offset: new AMap.Pixel(-25, -25),
          offset: new AMap.Pixel(-36, -36),
          position: [extData.longitude, extData.latitude],
          draggable: true,
          topWhenClick: true
        })
        // console.log(`${this.anchorsIconUrlList[extData.anchorTypeId]}&status=${extData.anchorStatus}${extData.isSelect ? 1 : 0}`)
        marker.setExtData(extData)

        /**
         * 标记点拖动监听函数
         * @author chend(cdhahaha@163.com)
         * @createDate 2018-07-25
         */
        marker.on('dragging', e => {
          if (this.markerChangeTag !== 'normal') return
          let tmpExtData = e.target.getExtData()
          tmpExtData.latitude = e.lnglat.lat
          tmpExtData.longitude = e.lnglat.lng
          this.achorsInfo = tmpExtData
        })

        /**
         * 标记点鼠标点下监听函数
         * @author chend(cdhahaha@163.com)
         * @createDate 2018-07-25
         */
        marker.on('click', this.selectMarkerFn)
        /**
         * 标记点鼠标点下监听函数
         * @author chend(cdhahaha@163.com)
         * @createDate 2018-07-25
         */
        marker.on('dragstart', this.selectMarkerFn)

//        this.cluster.addMarker(marker)

//        this.clusterMarkers.push(marker)

        return marker
      },
      /**
       * 标注信息面板点击事件
       * @author chend(cdhahaha@163.com)
       * @createDate 2018-08-08
       * @param      {String}   关闭/保存/删除/关联/预览
       */
      clickEvent (type) {
        switch (type) {
          case 'showAnchors':
            this.selectMarkerFn({target: this.selectMarker, type: 'click'})
            break
          case 'save':
            this.saveMarkerMsg()
            break
          case 'delete':
            this.deleteMarkerMsg()
            break
          case 'link':
            this.linkMarkerMsg()
            break
          case 'preview':
            this.previewMarkerMsg()
            break
        }
      },
      /**
       * 根据anchorId获取锚点详情
       */
      pointDetailGet(anchorId) {
        return this.$request.anchorPointDetailGet(anchorId)
      },
      /**
       *预览锚点事件
       */
      previewMarkerMsg () {
        this.pointerCheckedList.entranceIsPopUp === 'T' ? this.qtShow('preview') : this.iframeShow('preview')
      },
      /**
       * 关联锚点事件
       */
      linkMarkerMsg () {
        this.pointerCheckedList.relationIsPopUp === 'T' ? this.qtShow('link') : this.iframeShow('link')
      },
      /**
       * 删除锚点事件
       */
      deleteMarkerMsg () {
        this.$confirm('此操作将删除当前选择标注, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          closeOnClickModal: false,
          type: 'warning'
        }).then(() => {
          // console.log(this.selectMarker.getExtData())
          this.$request.anchorPointDelete(this.selectMarker.getExtData().anchorId).then(res => {
            console.log(res)
            this.selectMarkerOrig = null
            this.achorsInfo = {}
            this.showAnchors = false
            this.map.remove(this.selectMarker)
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      /**
       * 修改锚点update方法
       */
      markerUpdate () {
        let params = {}
        if (!this.achorsInfo.anchorName) {
          this.$message({
            type: 'warning',
            message: '锚点名称不能为空'
          })
          return 'null'
        }
        params.areaCityId = this.editData.areaCityId
        params.areaCountyId = this.editData.areaCountyId
        params.areaTownId = this.editData.areaTownId
        params.areaWayId = this.editData.areaWayId
        params.anchorDesc = this.achorsInfo.anchorDesc
        params.anchorName = this.achorsInfo.anchorName
        params.anchorId = this.achorsInfo.anchorId
        params.anchorTypeId = this.pointerCheckedList.anchorTypeId
        params.latitude = this.achorsInfo.latitude
        params.longitude = this.achorsInfo.longitude
        params.height = this.achorsInfo.height
        params.mapScale = this.achorsInfo.mapScale
        params.relationBusinessData = ''
        if (this.tabIndex === '2d') {
          params.isMapModel2d = 'T'
          return this.$request.anchorPoint2DUpdate(params).then(res => {
            this.setMarkerState({
              marker: this.selectMarker,
              changeArr: [{
                label: 'anchorStatus',
                value: res.anchorStatus
              }, {
                label: 'isSelect',
                value: true
              }, {
                label: 'anchorName',
                value: res.anchorName
              }]
            })
            this.$message({
              type: 'success',
              message: '修改成功!'
            })
            this.selectMarkerOrig = JSON.parse(JSON.stringify(this.selectMarker.getExtData()))
          }).catch(e => {
            this.$message({
              type: 'error',
              message: '修改失败!'
            })
          })
        } else if (this.tabIndex === '3d') {
          params.isMapModel2d = 'F'
          return this.$request.anchorPoint3DUpdate(params).then(res => {
            console.log(res, '修改成功')
            this.$message({
              type: 'success',
              message: '修改成功!'
            })
            this.setMarkerState({
              marker: this.selectMarker,
              changeArr: [{
                label: 'anchorStatus',
                value: res.anchorStatus
              }, {
                label: 'isSelect',
                value: true
              }, {
                label: 'anchorName',
                value: res.anchorName
              }]
            })
            this.selectMarker.setHeight(this.achorsInfo.height)
            this.selectMarkerOrig = JSON.parse(JSON.stringify(this.selectMarker.getExtData()))
          }).catch(e => {
            this.$message({
              type: 'error',
              message: '修改失败!'
            })
          })
        }
      },
      /**
       * 保存锚点事件
       */
      saveMarkerMsg () {
        if (!this.achorsInfo.anchorName) {
          console.log(this.achorsInfo, 'achorsInfo!!!!!!!!!!!')
          this.$message({
            type: 'warning',
            message: '锚点名称不能为空'
          })
          return
        }
        this.$confirm('保存锚点信息', '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          callback: action => {
            if (action === 'confirm') this.markerUpdate()
          }
        })
      },
      /**
       * 锚点事件回调
       */
      markerHandle (e) {
        var position = [e.lnglat.lng, e.lnglat.lat]
        this.showUlFlag = !this.showUlFlag
        let extData = {
          longitude: e.lnglat.lng,
          latitude: e.lnglat.lat,
          mapScale: this.pointerCheckedList.mapScale,
          anchorStatus: '01',
          anchorTypeId: this.pointerCheckedList.anchorTypeId,
          anchorIconUrl: this.pointerCheckedList.anchorIconUrl
        }
        if (this.tabIndex === '3d') {
          extData.height = 100
          this.$request.anchorPoint3DAdd(this.pointerCheckedList.anchorTypeId, extData.height, e.lnglat.lat, e.lnglat.lng).then(res => {
            console.log(res, 'res3D!!!!!!!!!!!!')
            extData.anchorId = res.anchorId
            this.currentMarkerIdList.push(res.anchorId)
            let tmpMarker = this.setMarker({
              extData
            })
            this.map.add(tmpMarker)
          })
        } else if (this.tabIndex === '2d') {
          this.$request.anchorPoint2DAdd(this.pointerCheckedList.anchorTypeId, e.lnglat.lat, e.lnglat.lng).then(res => {
            console.log(res, 'res2D!!!!!!!!!!!!')
            extData.anchorId = res.anchorId
            this.currentMarkerIdList.push(res.anchorId)
            let tmpMarker = this.setMarker({
              extData
            })
            this.map.add(tmpMarker)
          })
        }
      },
      /**
       * 动态绑定和移除锚点监听器
       */
      markerListener ({ctx, type}) {
        if (type === 'add') {
          if (!this.listenerFlag) {
            ctx.on('click', this.markerHandle)
            this.listenerFlag = true
          }
        } else {
          // console.log('remove')
          ctx.off('click', this.markerHandle)
          this.listenerFlag = false
        }
      },
      /**
       *  地图上锚点初始化事件
       */
      markersInit (all) {
        var mapBounds = this.map.getBounds()
        let actualMapScale = parseInt(this.map.getZoom())
        let tmpbounds = {}
        this.oldMapBounds = all ? null : this.oldMapBounds
        if (!mapBounds) return
        tmpbounds.isMapModel2d = 'T'
        if (this.map.AmbientLight) {
          mapBounds = this.$utils.covertToRect(mapBounds.bounds[0], mapBounds.bounds[1], mapBounds.bounds[2], mapBounds.bounds[3])
          tmpbounds.isMapModel2d = 'F'
        }
        tmpbounds.anchorTypeId = this.pointerCheckedList.anchorTypeId
        tmpbounds.actualMapScale = this.$utils.MAPSCALEMAP[actualMapScale]
        tmpbounds.isShowNotRelation = this.pointerCheckedList.showCheck.indexOf('showUnLink') > -1 ? 'T' : 'F'
        tmpbounds.isShowNotEdit = this.pointerCheckedList.showCheck.indexOf('showUnEdit') > -1 ? 'T' : 'F'
        tmpbounds.mapScaleList = this.pointerCheckedList.showList
        tmpbounds.nowLatitudeEnd = mapBounds.northeast.lat
        tmpbounds.nowLatitudeStart = mapBounds.southwest.lat
        tmpbounds.nowLongitudeEnd = mapBounds.northeast.lng
        tmpbounds.nowLongitudeStart = mapBounds.southwest.lng
        tmpbounds.oldLatitudeEnd = this.oldMapBounds && this.oldMapBounds.northeast.lat
        tmpbounds.oldLatitudeStart = this.oldMapBounds && this.oldMapBounds.southwest.lat
        tmpbounds.oldLongitudeEnd = this.oldMapBounds && this.oldMapBounds.northeast.lng
        tmpbounds.oldLongitudeStart = this.oldMapBounds && this.oldMapBounds.southwest.lng
        console.time('time')
        return this.$request.anchorPointMoreListGet(tmpbounds).then(res => {
          this.oldMapBounds = mapBounds
          console.timeEnd('time')
          return this.isMarkerInMap(res.resultList)
        })
      },
      /**
       * 判断锚点是否已经在地图上渲染过 只对未在currentMarkerIdList的锚点进行渲染
       */
      async isMarkerInMap (res) {
        /**
         * 判断地图上是否已经存在这个点
         * @type {Array}
         */
        let tmpMarkerList = []
        let tmpIdList = []
        console.time('!!!!!!!!!')
        res.map((item) => {
          if (this.currentMarkerIdList.indexOf(item.anchorId)===-1) {
            item.mapScale = item.mapScale ? item.mapScale : this.pointerCheckedList.mapScale
            let extData = item
            var marker = this.setMarker({
                extData
            })
            tmpMarkerList.push(marker)
            tmpIdList.push(item.anchorId)
          }
        })
        this.currentMarkerIdList = this.currentMarkerIdList.concat(tmpIdList)
        this.map.add(tmpMarkerList)
        this.markerShowManage()
      },
      /**
       * 锚点的显示隐藏
       */
      markerShowManage () {
        let actualMapScale = parseInt(this.$utils.MAPSCALEMAP[parseInt(this.map.getZoom())])
        let removeMarkers = []
        this.map.getAllOverlays().forEach(v => { //this.map.getAllOverlays() this.cluster.getMarkers()
          var extData = v.getExtData()
          switch (extData.anchorStatus) {
            case '01':
              if (this.pointerCheckedList.showCheck.indexOf('showUnEdit') === -1) {
//                this.currentMarkerIdList.splice(this.currentMarkerIdList.indexOf(extData.anchorId), 1)
//                removeMarkers.push(v)
                v.hide()
              } else {
                v.show()
              }
              break
            case '02':
              if (this.pointerCheckedList.showCheck.indexOf('showUnLink') === -1) {
//                this.currentMarkerIdList.splice(this.currentMarkerIdList.indexOf(extData.anchorId), 1)
//                removeMarkers.push(v)
                v.hide()
              } else {
                v.show()
              }
              break
            case '03':
              if ((this.pointerCheckedList.showList.indexOf(extData.mapScale) === -1) && (actualMapScale > parseInt(extData.mapScale))) {
//                this.currentMarkerIdList.splice(this.currentMarkerIdList.indexOf(extData.anchorId), 1)
//                removeMarkers.push(v)
                v.hide()
              } else {
                v.show()
              }
              break
          }
        })
      },
      /**
       * 编辑框值发生变化 地图上锚点相应调整
       */
      changeAnchorsMarkerPosition (position, height) {
        this.selectMarker.setPosition(position)
        this.tabIndex === '3d' && this.selectMarker.setHeight(height)
      },
      /**
       * 打开或者关闭框选功能
       */
      openAndClose () {
        this.openAndCloseFlag ? this.closeSelectZoom() : this.openSelectZoom()
        this.openAndCloseFlag = !this.openAndCloseFlag
      },
      /**
       * 启用框选功能
       */
      openSelectZoom () {
        this.map.plugin(["AMap.MouseTool"], () => {
          var isDrawRec = false
          this.mouseTool = new AMap.MouseTool(this.map)
          this.mouseTool.rectangle()
          this.selectZoomMouseDownHandler = (e) => {
            this.ancSelectMarkers = []
            if (isDrawRec) {
              var Polygons = this.map.getAllOverlays('Polygon')
              for (var i = 0, l = Polygons.length; i < l - 1; i++) {
                this.map.remove(Polygons[i])
              }
              isDrawRec = false
            }
          }
          this.selectZoomDrawHandler = (e) => {
            var allMarker = this.map.getAllOverlays('Marker')
            isDrawRec = true
            allMarker.forEach(v => {
              if (e.obj.contains(v.getPosition())) {
                this.ancSelectMarkers.push(v)
              }
            })
          }
          this.map.on('mousedown', this.selectZoomMouseDownHandler)
          this.mouseTool.on('draw', this.selectZoomDrawHandler)
        })
      },
      /**
       * 关闭框选事件
       */
      closeSelectZoom () {
        if (!this.mouseTool) {
          return
        }
        var Polygons = this.map.getAllOverlays('Polygon')
        this.ancSelectMarkers = []
        for (var i = 0, l = Polygons.length; i < l; i++) {
          this.map.remove(Polygons[i])
        }
        this.map.off('mousedown', this.selectZoomMouseDownHandler)
        this.mouseTool.off('draw', this.selectZoomDrawHandler)
        this.mouseTool.close()
      },
      maximumInit () {
        if (this.tabIndex === '2d') {
          this.markerSetData2D.maximum = Math.floor((this.$refs.container_2d.clientWidth - 320) / 80)
          this.$set(this.markerSetData2D, 'maxChange', true)
        } else if (this.tabIndex === '3d') {
          this.markerSetData3D.maximum = Math.floor((this.$refs.container_3d.clientWidth - 320) / 80)
          this.$set(this.markerSetData3D, 'maxChange', true)
        }
      },
      /**
       * 给地图添加事件
       * @param ctx
       */
      mapEventHandle(ctx) {
        ctx.on('moveend', e => {
          console.log(e, 'moveend')
          if (!this.pointerCheckedList) return
          this.throttleEventHandle()
        })
        ctx.on('resize', e => {
          this.maximumInit()
          if (!this.pointerCheckedList) return
          this.throttleEventHandle()
        })
        ctx.on('zoomend', e => {
          console.log('zoomend', e)
          if (!this.pointerCheckedList) return
          this.throttleEventHandle()
        })
      },
      /**
       * 获取锚点类型
       */
      async getAnchorTypeQuery () {
        await this.$request.dictDetailList({dictCode: 'MAP_SCALE'}).then(dicRes => {
          this.mapScaleArr = dicRes
        })
        await this.$request.anchorType2DListGet().then(res => {
          console.log(res)
          res.recordList.map(v => {
            v.msgs = this.mapScaleArr
            v.showCheck = ['showName', 'showUnLink', 'showUnEdit']
            v.showList = []
            v.showAll = []
            this.anchorsIconUrlList[v.anchorTypeId] = v.anchorIconUrl
            return v
          })
          this.markerSetData2D.recordList = res.recordList
        })
        await this.$request.anchorType3DListGet().then(res => {
          console.log(res)
          res.recordList.map(v => {
            v.msgs = this.mapScaleArr
            v.showCheck = ['showName', 'showUnLink', 'showUnEdit']
            v.showList = []
            v.showAll = []
            this.anchorsIconUrlList[v.anchorTypeId] = v.anchorIconUrl
            return v
          })
          this.markerSetData3D.recordList = res.recordList
        })
        this.markerSetData = this.tabIndex === '3d' ? this.markerSetData3D : this.markerSetData2D
      },
      /**
       * websocket长连接
       * @author chend(cdhahaha@163.com)
       * @createDate 2018-09-21
       */
      onWebSocket () {
        window.webSocket.onopen = (e) => {
          console.log('webSocketChend', e)
        }
        window.webSocket.onmessage = this.linkCallBack
      },
      linkCallBack (e) {
        if(e.data === 'heartbeat') return
        var data = JSON.parse(e.data)
        if (data.isBindSuccess === 'true') {
          this.$message({
            message: '关联成功',
            type: 'success'
          })
          this.pointDetailGet(data.anchorId).then(res => {
            console.log(res)
            this.setMarkerState({
              marker: this.selectMarker,
              changeArr: [{
                label: 'anchorStatus',
                value: '03'
              }, {
                label: 'relationBusinessData',
                value: res.relationBusinessData
              }]
            })
            this.selectMarkerOrig.anchorStatus = res.anchorStatus
            this.selectMarkerOrig.relationBusinessData = res.relationBusinessData
          })
        } else {
          this.$message({
            message: '关联失败，请重试',
            type: 'warning'
          })
        }
      },
      /**
       * 初始化事件
       */
      init () {
        this.throttleEventHandle = this.$utils.throttle(this.markersInit, 500)
        this.map2D = new AMap.Map('container_2d', {
          resizeEnable: true,
          zoom: 10,
          center: [107.8838, 25.412239],
          mapStyle: 'amap://styles/d3fc11529eaf1d820d9d1d79da8a104c', // 设置地图的显示样式
          viewMode: '2D' // 使用3D视图
        })
        this.map3D = new AMap.Map('container_3d', {
          resizeEnable: true,
          center: [107.8838, 25.412239],
          zoom: 10,
          mapStyle: 'amap://styles/d3fc11529eaf1d820d9d1d79da8a104c', // 设置地图的显示样式
          viewMode: '3D' // 使用3D视图
        })
        this.maximumInit()
        this.mapEventHandle(this.map2D)
        this.mapEventHandle(this.map3D)
        this.KeywordLocationMapCenterPoint(this.map2D, 'pickerInput')
        this.KeywordLocationMapCenterPoint(this.map3D, 'pickerInput3D')
        this.map = this.tabIndex === '3d' ? this.map3D : this.map2D
        this.getZoomAndCenter()
        this.getAnchorTypeQuery()
        this.scaleTool(this.map)
        this.scaleTool(this.map3D)
        let _renderCluserMarker = (content) => {
          let icon = content.markers[0].getIcon().slice(0, content.markers[0].getIcon().indexOf('status=')) + 'status=030'
          let contentHtml = `<div style="width: 72px; height: 72px; background-image: url(${icon}); text-align: center; line-height: 32px; background-position: 0px 0px; color: rgb(0, 0, 0); font-size: 12px; cursor: pointer;">
                                 <p style="position: absolute; margin-top: 40px;width: 72px;text-align: center;color: #fff;font-size: 15px;">${content.count}</p></div>`
          content.marker.setContent(contentHtml)
        }
        this.cluster = this.cluster || new AMap.MarkerClusterer(this.map, [], {
          renderCluserMarker: _renderCluserMarker,
          gridSize: 80
        })
      }
    },
    watch: {
      pointerCheckedList (cur, old) {
        if (!old) this.markerListener({ctx: this.map, type: 'add'})
        if (!cur) return
        this.currentMarkerIdList = []
//        this.cluster.clearMarkers()
        this.selectMarkerOrig = null
        this.achorsInfo = {}
        this.showAnchors = false
        this.map.clearMap()
        this.markersInit('all')
//        this.markerShowManage(tmpPointTypeObj.anchorTypeId)
      },
      achorsInfo: {
        handler: function (cur, old) {
          if (!this.$utils.isEmptyObject(cur) && this.markerChangeTag === 'normal') {
            this.changeAnchorsMarkerPosition([cur.longitude, cur.latitude], cur.height)
          }
        },
        deep: true
      },
      tabIndex(cur) {
//        this.cluster.clearMarkers()
        this.map.clearMap()
        if (cur === '3d') {
          this.markerListener({ctx: this.map2D, type: 'remove'})
          this.map = this.map3D
          this.markerSetData = this.markerSetData3D
        } else {
          this.markerListener({ctx: this.map3D, type: 'remove'})
          this.map = this.map2D
          this.markerSetData = this.markerSetData2D
        }
//        this.cluster.setMap(this.map)
        this.selectMarkerOrig = null
        this.achorsInfo = {}
        this.showAnchors = false
        this.pointerCheckedList = ''
        this.getZoomAndCenter()
        if (!this.pointerCheckedList) return
        this.markersInit('all')
      }
    },
    mounted () {
      this.init()
      this.onWebSocket()
    },
    components: {
      markerSetPanel,
      locationPanel,
      anchorsBar,
      cameraList,
      markerList
    }
  }
</script>
<style rel="stylesheet/less" lang="less">
  .markerSetPanel {
    position: absolute;
    bottom: 20px;
    left: 240px;
  }
  .mapBox {
    position: absolute;
    height: 100%;
    width: 100%;
    /*缩放样式*/
    .amap-ui-control-position-lt, .amap-ui-control-position-tl {
      top: 180px !important;
      left: 40px !important;
    }
    .amap-ui-control-zoom {
      width: 40px !important;
    }
    .amap-ui-control-zoom a, .amap-ui-control-zoom-num {
      width: 40px !important;
      height: 50px !important;
      line-height: 50px !important;
    }
    /*比例尺样式*/
    .amap-scalecontrol {
      color: #fff;
      top: 200px;
      left: 40px;
    }
    .amap-marker-label {
      background-color: transparent;
      color: #fff;
      border: none;
      font-size: 14px;
    }
  }

  .cancelAllMarkers {
    position: absolute;
    z-index: 6;
    height: 100px;
    width: 100px;
    background-color: #fff;
    color: #222;
  }

  .markerSelect {
    position: relative;
    height: 46px;
    width: 46px;
    border-radius: 50%;
    border: 2px solid #0ff;
    box-shadow: 0 0 25px #0ff;
    > .iconMarkerUnedit {
      display: block;
      height: 20px;
      width: 20px;
      background: url('../../../assets/images/mapIconTest/2dUnedit.png') no-repeat center;
      position: absolute;
      left: 50%;
      top: 50%;
      z-index: 2;
    }
    > .iconMarkerUnlink {
      display: block;
      height: 20px;
      width: 20px;
      background: url('../../../assets/images/mapIconTest/2dUnlink.png') no-repeat center;
      position: absolute;
      left: 50%;
      top: 50%;
      z-index: 2;
    }
    > img {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate3D(-50%, -50%, 0);
      -ms-transform: translate3D(-50%, -50%, 0);
      -moz-transform: translate3D(-50%, -50%, 0);
      -webkit-transform: translate3D(-50%, -50%, 0);
      -o-transform: translate3D(-50%, -50%, 0);
      z-index: 1;
    }
  }

  .markerUnSelect {
    position: relative;
    height: 50px;
    width: 50px;
    > .iconMarkerUnedit {
      display: block;
      height: 20px;
      width: 20px;
      background: url('../../../assets/images/mapIconTest/2dUnedit.png') no-repeat center;
      position: absolute;
      left: 50%;
      top: 50%;
      z-index: 2;
    }
    > .iconMarkerUnlink {
      display: block;
      height: 20px;
      width: 20px;
      background: url('../../../assets/images/mapIconTest/2dUnlink.png') no-repeat center;
      position: absolute;
      left: 50%;
      top: 50%;
      z-index: 2;
    }
    > img {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate3D(-50%, -50%, 0);
      -ms-transform: translate3D(-50%, -50%, 0);
      -moz-transform: translate3D(-50%, -50%, 0);
      -webkit-transform: translate3D(-50%, -50%, 0);
      -o-transform: translate3D(-50%, -50%, 0);
      z-index: 1;
    }
  }

  /* 摄像头面板 */
  .cameraList {
    position: absolute;
    width: 60%;
    max-width: 700px;
    height: 60%;
    top: 20%;
    left: 50%;
    margin-left: -30%;
    z-index: 9999;
  }

  .ancSelectBox {
    position: absolute;
    bottom: 100px;
    left: 240px;
    background: url('../../../assets/images/mapIconTest/2dBoxChecked.png');
    background-size: 60px 60px;
    height: 60px;
    width: 60px;
    cursor: pointer;
    img {
      width: 40px;
      margin-top: 8px;
      margin-left: 12px;
    }
  }

  .ancUnSelectBox {
    position: absolute;
    bottom: 100px;
    left: 240px;
    background: url('../../../assets/images/mapIconTest/2dBox.png');
    background-size: 60px 60px;
    height: 60px;
    width: 60px;
    cursor: pointer;
    img {
      width: 40px;
      margin-top: 8px;
      margin-left: 12px;
    }
  }

  .markerList {
    position: absolute;
    top: 500px;
    left: 500px;
    z-index: 3;
  }
</style>
